package com.example.oss.service.impl;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.model.oss.FileInfo;
import com.example.oss.service.OssService;
import com.example.oss.storage.IStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private IStorage storage;

    @Value("${oss.aliyun.bucketName}")
    String bucketName;


    //上传文件同时获取图片路径
    @Override
    public FileInfo uploadFile(MultipartFile file) {
        FileInfo fileInfo = getFileInfo(file);
        try {
            storage.putObject(fileInfo.getBucketName(), fileInfo.getFileName(), file.getInputStream(), fileInfo.getContentType());
            String publicUrl = getPublicUrl(fileInfo.getFileName());
            fileInfo.setFileUrl(publicUrl);
            return fileInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //得到上传文件的信息
    @Override
    public FileInfo getFileInfo(MultipartFile file){
        final String fileOriginalName = file.getOriginalFilename();
        String objectName = IdUtil.fastSimpleUUID();
        String fileName = objectName;
        String fileSuffix = fileOriginalName.substring(fileOriginalName.lastIndexOf(".") + 1);
        if (StrUtil.isNotEmpty(fileSuffix)) {
            fileName = objectName.concat(String.valueOf(CharUtil.DOT)).concat(fileSuffix);
        }
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileOriginalName("signle-"+objectName);
        fileInfo.setFileName(fileOriginalName);
        fileInfo.setFileSize(file.getSize());
        fileInfo.setContentType(file.getContentType());
        fileInfo.setStorage("aliyun");
        fileInfo.setBucketName(bucketName);
        return fileInfo;
    }
    @Override
    public String getPublicUrl(String objectName) {
        return storage.getPublicObjectUrl(bucketName, objectName);
    }

    @Override
    public String getSignedUrl(String objectName) {
        return storage.getSignedObjectUrl(bucketName, objectName);
    }

}
